#include "REG52.H"
sbit D = P1^0;
sbit C = P1^1;
sbit Motor_B = P1^2;
sbit A = P1^3;

sbit K1 = P3^1;
sbit K2 = P3^0;
sbit K3 = P3^2;
sbit K4 = P3^3;


 #define STEP_MOTOR_MAX_SPEED 1
 #define STEP_MOTOR_MIN_SPEED 5

void delay_10us(unsigned int x )
 {
     while (x--);
 }

 void delay_ms(unsigned int y)
 {
     unsigned int i,j;
     for ( i = y; i > 0; i--)
         for ( j = 110; j > 0; j--);
 }


 int which_key_press()
 {
	while(1)
 	{
        delay_10us(100);
        if(K1==0||K2==0||K3==0||K4==0)
        {
            delay_10us(1000);
            if(K1==0) return 1;
            if(K2==0) return 2;
            if(K3==0) return 3;
            if(K4==0) return 4;
        }
        return 0;
 	}	
 }

void step_motor_8_send_pulse(int x,int stepr)
{
        int temp = stepr;
        if (x == 1)
        {
            temp = 9-stepr;
        }
            switch (temp)
            {
                case 1: A = 1;Motor_B = 1 ;C = 1; D = 0;break;
                case 2: A = 1;Motor_B = 1 ;C = 0; D = 0;break;
                case 3: A = 1;Motor_B = 1 ;C = 0; D = 1;break;
                case 4: A = 1;Motor_B = 0 ;C = 0; D = 1;break;
                case 5: A = 1;Motor_B = 0 ;C = 1; D = 1;break;
                case 6: A = 0;Motor_B = 0 ;C = 1; D = 1;break;
                case 7: A = 0;Motor_B = 1 ;C = 1; D = 1;break;
                case 8: A = 0;Motor_B = 1 ;C = 1; D = 0;break;
                default:A = 1;Motor_B = 1 ;C = 1; D = 1;break; 
            } 
}
int motor_off()
{
    while(1)
    {
    int a = which_key_press();
    A = 1;Motor_B = 1 ;C = 1; D = 1;
    delay_10us(100);
    while (a == 4)
    {
          return 0;
    }
    }
}
int speed_adjusting(int x,int y)
{
    if (x==2)
    {
        delay_10us(100);
        if (y>STEP_MOTOR_MAX_SPEED)
        {
            y--;
            return y;
        }
    }
    if (x==3)
    {
        delay_10us(100);
        if (y<STEP_MOTOR_MIN_SPEED)
        {
            y++;
            return y;
        }
        
    }
    
}

int main()
{
    int steps = 1;
    int dir = 0;
    int key =0;
    int speed = 1;
    while (1)
    {
        key = which_key_press();
        if (key == 4)
        {
            delay_10us(15);
            if (key ==4)
            {
            motor_off();
            return 0;
            }
        }
        if (key == 1)
        {
            delay_10us(15);
            if (key == 1)
            {
               dir =! dir;
            }
        }
        if (key == 2)
        {
            delay_10us(15);
            if (key==2 && speed > STEP_MOTOR_MAX_SPEED)
            {
              speed--;
            }
        }
        if (key == 3)
        {
            delay_10us(15);
            if (key ==3 && speed < STEP_MOTOR_MIN_SPEED)
            {
              speed++;
            }
        }
        
        step_motor_8_send_pulse(dir,steps++); //在传参数时候++ 妙！
        if (steps > 8) steps =1;
        delay_ms(speed);
    }
}